import { _decorator, Component, Sprite, color, Label,Node,find,Vec3, PolygonCollider2D, instantiate, Prefab, tween} from 'cc';
import { buff } from './buff';
import { createEnemy } from './createEnemy';
const { ccclass, property } = _decorator;
@ccclass('boss')
export class boss extends Component {
    @property
    public health: number = 10000;
    
    // 玩家节点
    @property(Node)
    PlayerNode : Node = null;

    // boss发射的光波预制体
    @property(Prefab)
    guangboPre:Prefab = null;
    
    // buff节点
    buff:Node = null;

    // boss移动速度
    public moveSpeed = 280
    // boss的攻击力
    public attack = 30
    // 记录boss生成时的血量，用于计算百分比伤害
    public startHealth = 10000
    // 灼烧定时器
    burnTimer = null;
    // boss攻击定时器
    public bossATKTimer = null;
    // boss发射的光波的位置偏移量
    private atkX = 0
    // boss发射光波旋转角度
    private atkRotate = 0
    // boss光波攻击方向
    private fangxiangX = 0
    private fangxiangY = 0

    private collider: PolygonCollider2D = null;

    onLoad() {
        this.collider = this.getComponent(PolygonCollider2D);
        this.collider.enabled = true;
        // 通过find查找玩家节点，避免boss预制体挂载该脚本时无法设置玩家Node属性的值
        // this.PlayerNode = find('Canvas/me');
        // 记录初始血量
        this.startHealth = this.health
        this.bossAttack()
    }

    update(deltaTime: number) {
        // 获取玩家节点和boss节点的位置
        const playerPos = this.PlayerNode.position;
        const bossPos = this.node.position;
        // 计算boss节点到玩家节点的方向向量
        // 为玩家节点加上克隆可以避免一直重置玩家位置导致无法移动的问题
        const direction = playerPos.clone().subtract(bossPos);
        // 归一化方向向量
        const normalizedDirection = direction.normalize();
        // 更新boss节点的位置
        this.node.position = bossPos.add(normalizedDirection.multiplyScalar(this.moveSpeed * deltaTime));
        // 调整玩家节点
        this.PlayerNode = find('Canvas/me');
        let playerWPos = this.PlayerNode.position.clone()
        let bossWPos = this.node.position.clone()
        let jitui = 0// boss免疫击退
        if(playerWPos.x < bossWPos.x && playerWPos.y <= bossWPos.y){// boss在玩家右上方
            // this.node.setWorldPosition(bossWPos.x+jitui,bossWPos.y+jitui,0)
            this.node.setScale(1,1)//设置boss的面朝方向
            this.atkX = -78
            this.fangxiangX = -1500
            this.fangxiangY = -1500
        }else if(playerWPos.x < bossWPos.x && playerWPos.y > bossWPos.y){// boss在玩家右下方
            // this.node.setWorldPosition(bossWPos.x+jitui,bossWPos.y-jitui,0)
            this.node.setScale(1,1)//设置boss的面朝方向
            this.atkX = -78
            this.fangxiangX = -1500
            this.fangxiangY = 1500
        }else if(playerWPos.x > bossWPos.x && playerWPos.y <= bossWPos.y){// boss在玩家左上方
            // this.node.setWorldPosition(bossWPos.x-jitui,bossWPos.y+jitui,0)
            this.node.setScale(-1,1)//设置boss的面朝方向
            this.atkX = 78
            this.fangxiangX = 1500
            this.fangxiangY = -1500
        }else{// boss在玩家左下方
            // this.node.setWorldPosition(bossWPos.x-jitui,bossWPos.y-jitui,0)
            this.node.setScale(-1,1)//设置boss的面朝方向
            this.atkX = 78
            this.fangxiangX = -1500
            this.fangxiangY = 1500
        }
    }
    // 受到伤害
    takeDamage(damage: number,node,type,ex) {// 收到伤害值，武器节点，武器类型，武器特殊伤害类型
        let percentAttack = 0
        if(ex == "Burning"){// 火球的灼烧
            // this.Burning()// boss免疫灼烧
        }else if(ex == '0.03' || ex == '0.02' || ex == '0.01'){// 武器的百分比真伤
            percentAttack = Math.floor(this.startHealth * (Number(ex)-0.01))// boss对真伤有一定抵抗
            this.health -= percentAttack
        }else{// 未解锁ex技能
            percentAttack = 0
        }
        this.health -= Math.floor(damage)
        // 播放受击动画
        this.playHitAnimation(Math.floor(damage),type,percentAttack);
        // console.log("-10")wwwww
        if (this.health <= 0) {
            this.die();
        }
    }
    // 灼烧伤害
    // Burning(){// 灼烧伤害是扣除boss当前生命的10%
    //     clearInterval(this.burnTimer)
    //     let nums = 0
    //     this.burnTimer = setInterval(() => {
    //         if(!this.node)return
    //         if(nums >= 5){// 持续5秒的灼烧
    //             clearInterval(this.burnTimer)
    //         }
    //         if(!this.node){
    //             clearInterval(this.burnTimer)
    //         }
    //         if(this.node){
    //             this.node.children[0].getComponent(Label).color = color(255,128,0)// 灼烧伤害颜色，橙色
    //             setTimeout(() => {
    //                 if(this.node){
    //                     this.node.children[0].getComponent(Label).string = ``
    //                 }
    //             }, 200);
    //         }
    //         if(this.node){
    //             this.node.getComponent(Sprite).color = color(255,128,0)
    //             setTimeout(() => {
    //                 if(this.node){
    //                     this.node.getComponent(Sprite).color = color(0,0,0)
    //                 }
    //             }, 200);
    //         }
    //         if(this.node){// 每秒灼烧伤害为当前生命的5%
    //             this.node.children[0].getComponent(Label).string = `-${Math.floor(this.health * .05)}`
    //         }
    //         if(this.node){
    //             this.health -= Math.floor(this.health * .1)
    //         }
    //         // 烧死了就销毁节点
    //         if (this.health <= 0) {
    //             this.die();
    //             clearInterval(this.burnTimer)
    //         }
    //         // 灼烧次数加1
    //         nums+=1
    //     }, 1000);
    // }
    private playHitAnimation(damage,type,percentAttack) {
        // 播放受击动画或效果
        if(type == 'physics'){// 物理伤害
            this.node.children[0].getComponent(Label).color = color(255,0,0)
            this.node.getComponent(Sprite).color = color(255,0,0)
        }else if(type == 'magic'){// 法术伤害
            this.node.children[0].getComponent(Label).color = color(0,0,255)
            this.node.getComponent(Sprite).color = color(0,0,255)
        }
        this.node.children[0].getComponent(Label).string = `-${damage+percentAttack}`
        // boss被击退
        // const bossPos = this.node.position.clone();
        // const attackerPos = node.position.clone();
        // attackerPos.y-=600
        // 玩家和boss的世界坐标
        
        // console.log(playerWPos,'玩家位置')
        // console.log(bossWPos,'boss位置')
        // 计算击退方向（从攻击者指向boss）
        // let dir = bossPos.subtract(attackerPos).normalize();
        // this.node.eulerAngles = new Vec3(0, 0,node.eulerAngles)
        // 通过判断玩家和boss世界坐标的位置左右高低来设置boss被"击退的方向"
        // 击退距离为 抗性*击退距离
        // let jitui = this.moveSpeed/4*this.kangxing
        
        // 击退位移
        // this.node.setPosition(bossPos.add(dir.multiplyScalar(this.moveSpeed)));
        
        setTimeout(()=>{
            if(this.node){
                this.node.getComponent(Sprite).color = color(255,255,255)
                this.node.children[0].getComponent(Label).string = ``
            }
        },200)
    }
    // boss会发射光波攻击玩家
    bossAttack(){
        this.bossATKTimer = setInterval(() => {
            if(!this.guangboPre){
                clearInterval(this.bossATKTimer)
                return
            }
            let atk = instantiate(this.guangboPre)
            atk.setPosition(this.node.position.clone().x+this.atkX,this.node.position.clone().y)
            // this.node.addChild(atk)
            this.PlayerNode = find('Canvas/me');
            // 敌人攻击挂载节点
            let enemyATK = find('Canvas/enemyATK')
            enemyATK.addChild(atk)
            // 获取玩家节点和敌人节点的位置
            let playerPos = this.PlayerNode.position.clone();
            // console.log(playerPos,1)
            // playerPos.x = -playerPos.x
            // playerPos.y = -playerPos.y
            // console.log(playerPos,2)
            let atktween = tween(atk)
            // atk.eulerAngles = new Vec3(0, 0, this.atkRotate)
            // this.atkRotate += 36
            // if(this.atkRotate >= 360){
            //     this.atkRotate -= 360
            // }

            // atktween.to(10,{position:playerPos}).call(()=>{
            atktween.to(10,{position:new Vec3(this.fangxiangX,this.fangxiangY,0)}).call(()=>{
                // console.log(atk.position)
                atk.destroy()
            })
            atktween.start()

            // 为玩家节点加上克隆可以避免一直重置玩家位置导致无法移动的问题
            // const direction = playerPos.clone().subtract(enemyPos);
            // 归一化方向向量
            // const normalizedDirection = direction.normalize();
            // 更新敌人节点的位置
            // this.node.position = enemyPos.add(normalizedDirection.multiplyScalar(this.moveSpeed));
        }, 1000);
    }

    private die() {
        // 死亡处理
        if(!this.node){
            clearInterval(this.bossATKTimer)
            return
        }
        if(this.node){
            this.node.destroy();
        }
        let createEnemyNode:Node = find('Canvas')
        createEnemyNode.getComponent(createEnemy).isBoss = false// boss死亡后可继续生成boss
        if(createEnemyNode.getComponent(createEnemy).endless){//无尽模式在boss死亡后重新开始生成敌人
            createEnemyNode.getComponent(createEnemy).startCreate()
        }
        // boss死亡，通过展示youWin界面
        this.buff = find('Canvas/buff')
        this.buff.getComponent(buff).youWin()
    }
}